package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @GetMapping("hi")
    public String hi(){
        return "hi";
    }


    @GetMapping("/list")
    public PageDTO<Item> SelectPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size){
        //分页查询
        Page<com.hmall.item.pojo.Item> result = itemService.page(new Page<>(page, size));
        //封装并返回
        return new PageDTO(result.getTotal(),result.getRecords());
    }


    @GetMapping("/{id}")
    public Item getById(@PathVariable("id") Long id){
        System.out.println("请求进来了");
        return itemService.getById(id);
    }

    //新增商品
    @PostMapping
    public void addStorage(@RequestBody Item item){
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(2);
        //新增
        itemService.save(item);
    }

    //商品上架和下架
    @PutMapping("/status/{id}/{status}")
    public void putaway(@PathVariable("id") Long id,@PathVariable("status") int status){
        itemService.updateStatus(id,status);
    }

    //修改商品
    @PutMapping
    public void updateGoods(@RequestBody Item item){
        System.out.println(item.getId());
        item.setUpdateTime(new Date());
        item.setStatus(null);
        //更新
        itemService.updateById(item);
    }

    //删除商品
    @DeleteMapping("{id}")
    public void deleteGoods(@PathVariable Long id){
        itemService.removeById(id);
    }

    @PutMapping("/stock/{itemId}/{num}")
    public void updateStock(@PathVariable("itemId") Long itemId,@PathVariable("num") Integer num){
        itemService.updateStock(itemId,num);
    }

}
